<template>
    <div :id="domName" style="width: 100%; height: 100%"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import _ from 'lodash-es'
import { ref, toRefs, markRaw, onMounted, watch, onBeforeUnmount } from 'vue'
const props = defineProps({
    domName: {
        type: String,
        default: '',
    },
    option: {
        type: Object,
        default: () => {},
    },
})
const { domName, option } = toRefs(props)
//图表实例
const myChart = ref<any>()
const throttleValue = ref()

watch(
    option,
    (newVal: any) => {
        if (newVal && myChart.value) {
            myChart.value.setOption(newVal, { notMerge: true })
        }
    },
    { deep: true },
)

onMounted(() => {
    initChart()
    throttleValue.value = _.debounce(resize, 100)
    window.addEventListener('resize', throttleValue.value)
})
//释放图表
onBeforeUnmount(() => {
    window.removeEventListener('resize', throttleValue.value)
    if (!myChart.value) {
        return
    }
    myChart.value.dispose()
    myChart.value = null
})
//初始化图表
const initChart = () => {
    const chartEle = document.getElementById(domName.value)
    myChart.value = markRaw(echarts.init(chartEle))
    myChart.value.setOption(option.value, { notMerge: true })
}

const resize = () => {
    myChart.value?.resize()
}
</script>
